package send.weixin.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import send.weixin.model.request.TextMessage;
import send.weixin.service.WeChatService;
import send.weixin.util.MessageUtil;
import send.weixin.util.WeChatMsgUtil;
import sys.model.Questionnaire;
import sys.service.QuestionnaireService;


/**
 * 微信核心 web 入口
 *
 * @author leson
 * @see 用户微信接口的相关接入工作。
 */
@Controller
@RequestMapping("/wechat")
public class WeChatController {
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private QuestionnaireService questionnaireService;
    /**
     * 微信平台接入
     */
    @RequestMapping(value="/get",method = { RequestMethod.POST,
            RequestMethod.GET })
    public void get(HttpServletRequest request,HttpServletResponse
            response) throws IOException {
        //获取微信后台传入的四个参数
        String method = request.getMethod();
        if("GET".equalsIgnoreCase(method)) {
            System.out.println("===>微信get请求");
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            String echostr = request.getParameter("echostr");
            System.out.println(signature+","+timestamp+","+nonce+","+echostr);
            boolean flag = weChatService.checkSignature(signature, timestamp, nonce);
            PrintWriter p = null;
            try {
                p = response.getWriter();
                if(flag){
                    p.print(echostr);//注意此处必须返回echostr以完成验证
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        else{
            System.out.println("===>微信post===>用户消息===>");
            // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");

            // 调用核心业务类接收消息、处理消息
            TextMessage t= WeChatMsgUtil.processRequest(request);
        System.out.println("用户微信id==>"+t.getToUserName());

            if(t!=null&&t.getMsgType().equals(MessageUtil.RESP_MESSAGE_TYPE_LINK)){
                t.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
                System.out.println("===>微信查询接口:"+"问卷名===>"+t.getContent());
                if(t.getContent().equals("")){
                    t.setContent("请在#号后面加上要查询的问卷名");
                }
                else {
                    Questionnaire q=questionnaireService.selectByname(t.getContent().trim());
                    if(q==null){
                        t.setContent("未找到该问卷,请检查问卷名");
                    }
                    else {
                        StringBuffer url = request.getRequestURL();
                        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
                        String questionUrl = tempContextUrl + "/Question/getQuestionnaire?id=" + q.getId();
                        t.setContent("打开问卷("+q.getTitle()+")链接:  " + questionUrl);
                    }
                }
            }
            if(t.getToUserName().equals("oIMqNv0JRNSJm93HkqgBXVAh8AMc")){//宝宝进来
                String con="";
                int i=(int)((Math.random()*9+1));
                switch(i){
                    case 1: {con="宝宝!!!";break; }
                    case 2: {con="宝宝!你最棒！";break; }
                    case 3: {con="我知道你是宝宝";break; }
                    case 4: {con="你好！";break; }
                    case 5: {con="你再发一条试试！";break; }
                    case 6: {con="我还是只会回 宝宝！";break; }
                    case 7: {con="再发我还是只会回宝宝";break; }
                    case 8: {con="你敢不敢再发一条！ 宝宝！";break; }
                    case 9: {con="宝宝!~~~~";break; }
                }
                t.setContent("特殊用户--"+con+"---"+t.getContent());
            }

            else if(t.getToUserName().equals("oIMqNvyAvzja0HBNBlcZ4JaFfHks")){//
                String con="";
                int i=(int)((Math.random()*9+1));
                switch(i){
                    case 1: {con="特殊用户!!!";break; }
                    case 2: {con="暂无任何权限！";break; }
                    case 3: {con="我知道你是谁";break; }
                    case 4: {con="再发一条";break; }
                    case 5: {con="你再发一条试试！";break; }
                    case 6: {con="我还是只会回你再发一条！";break; }
                    case 7: {con="只有这个功能";break; }
                    case 8: {con="你敢不敢再发一条！！";break; }
                    case 9: {con="真的没有其他功能!~~~~";break; }
                }
                t.setContent("待审核用户---"+con+"---"+t.getContent());
            }
            else if(t.getToUserName().equals("oIMqNv1HU-_aeGxSJFiydttMt9Fg")){//
                String con="";
                int i=(int)((Math.random()*9+1));
                switch(i){
                    case 1: {con="特殊用户!!!";break; }
                    case 2: {con="特殊用户！";break; }
                    case 3: {con="特殊用户";break; }
                    case 4: {con="特殊用户";break; }
                    case 5: {con="特殊用户！";break; }
                    case 6: {con="特殊用户！";break; }
                    case 7: {con="特殊用户";break; }
                    case 8: {con="特殊用户！！";break; }
                    case 9: {con="特殊用户!~~~~";break; }
                }
                t.setContent(con+"---"+t.getContent());
            }
           // System.out.println(t.getContent());
            String respXml= MessageUtil.messageToXml(t);
            // 响应消息
            PrintWriter out = response.getWriter();
            out.print(respXml);
            out.close();
        }
        }

    }
